import { ref } from 'vue';
import { message } from 'ant-design-vue';
import {
  auditUploadRecordEntrust,
  finalAuditUploadRecordEntrust,
  entrustClient,
  countEntrustClient,
  getEntrustByAId,
  type OneClickEntrustParams,
  type OneClickEntrustResult
} from '../server/api';
import { useScheduledTask } from './useScheduledTask';

export function useOneClickEntrust() {
  const loading = ref(false);
  const result = ref<OneClickEntrustResult | null>(null);

  const { executeTask: executeScheduledTask } = useScheduledTask();

  /**
   * 执行一键委案流程
   * @param params 一键委案参数
   * @returns Promise<OneClickEntrustResult>
   */
  const executeOneClickEntrust = async (params: OneClickEntrustParams): Promise<OneClickEntrustResult> => {
    loading.value = true;
    result.value = null;

    const stepsResult = {
      preAudit: { success: false, message: '' },
      finalAudit: { success: false, message: '' },
      entrust: { success: false, message: '' },
      scheduledTask: { success: false, message: '' }
    };

    try {
      // 检查是否有案件ID
      if (!params.caseId) {
        throw new Error('缺少案件ID，无法执行一键委案流程');
      }

      // 步骤1: 初审
      console.log('开始执行初审...');
      try {
        const preAuditResult = await auditUploadRecordEntrust({
          id: params.caseId,
          state: 'AUDIT_SUCCESS',
          tsToken: params.tsToken
        });

        if (preAuditResult.success) {
          stepsResult.preAudit = { success: true, message: '初审成功' };
          console.log('初审成功');
        } else {
          stepsResult.preAudit = { success: false, message: preAuditResult.message || '初审失败' };
          throw new Error('初审失败');
        }
      } catch (error) {
        const errorMsg = error instanceof Error ? error.message : '初审失败';
        stepsResult.preAudit = { success: false, message: errorMsg };
        throw new Error(`初审失败: ${errorMsg}`);
      }

      // 步骤2: 终审
      console.log('开始执行终审...');
      try {
        const finalAuditResult = await finalAuditUploadRecordEntrust({
          id: params.caseId,
          state: 'AUDIT_SUCCESS',
          tsToken: params.tsToken
        });

        if (finalAuditResult.success) {
          stepsResult.finalAudit = { success: true, message: '终审成功' };
          console.log('终审成功');
        } else {
          stepsResult.finalAudit = { success: false, message: finalAuditResult.message || '终审失败' };
          throw new Error('终审失败');
        }
      } catch (error) {
        const errorMsg = error instanceof Error ? error.message : '终审失败';
        stepsResult.finalAudit = { success: false, message: errorMsg };
        throw new Error(`终审失败: ${errorMsg}`);
      }

      // 步骤3: 委案
      console.log('开始执行委案...');
      try {
        // 首先获取委案初始化数据
        const countResult = await countEntrustClient({
          loanIds: [params.caseId],
          tsToken: params.tsToken
        });

        if (!countResult.success) {
          throw new Error('获取委案初始化数据失败');
        }

        // 执行委案
        const entrustParams = {
          entrustBId: params.entrustBId,
          isInvalidRule: params.isInvalidRule,
          loanIds: [params.caseId],
          batchId: '',
          batchName: params.batchName,
          tsToken: params.tsToken
        };

        const entrustResult = await entrustClient(entrustParams);

        if (entrustResult.success) {
          stepsResult.entrust = { success: true, message: '委案成功' };
          console.log('委案成功');
        } else {
          stepsResult.entrust = { success: false, message: entrustResult.message || '委案失败' };
          throw new Error('委案失败');
        }
      } catch (error) {
        const errorMsg = error instanceof Error ? error.message : '委案失败';
        stepsResult.entrust = { success: false, message: errorMsg };
        throw new Error(`委案失败: ${errorMsg}`);
      }

      // 步骤4: 执行定时任务
      console.log('开始执行定时任务...');
      try {
        const taskSuccess = await executeScheduledTask();
        if (taskSuccess) {
          stepsResult.scheduledTask = { success: true, message: '定时任务执行成功' };
          console.log('定时任务执行成功');
        } else {
          stepsResult.scheduledTask = { success: false, message: '定时任务执行失败' };
          console.warn('定时任务执行失败');
        }
      } catch (error) {
        const errorMsg = error instanceof Error ? error.message : '定时任务执行失败';
        stepsResult.scheduledTask = { success: false, message: errorMsg };
        console.error('定时任务执行失败:', error);
      }

      // 判断整体执行结果
      const allStepsSuccess = Object.values(stepsResult).every(step => step.success);
      
      const finalResult: OneClickEntrustResult = {
        success: allStepsSuccess,
        message: allStepsSuccess ? '一键委案执行成功' : '一键委案执行完成，但部分步骤失败',
        caseId: params.caseId,
        steps: stepsResult
      };

      result.value = finalResult;
      return finalResult;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '执行失败，请重试';
      console.error('一键委案执行失败:', error);
      
      const finalResult: OneClickEntrustResult = {
        success: false,
        message: errorMessage,
        caseId: params.caseId,
        steps: stepsResult
      };

      result.value = finalResult;
      return finalResult;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取委案商列表
   * @returns Promise<Array<{id: string, name: string}>>
   */
  const getEntrustList = async (): Promise<Array<{id: string, name: string}>> => {
    try {
      const result = await getEntrustByAId({
        tsToken: localStorage.getItem('tsToken') || ''
      });

      if (result.success && result.result) {
        return (result.result || []).map((item: any) => ({
          id: item.customerId,
          name: item.customerName
        }));
      }
      return [];
    } catch (error) {
      console.error('获取委案商列表失败:', error);
      message.error('获取委案商列表失败');
      return [];
    }
  };

  /**
   * 重置状态
   */
  const reset = () => {
    loading.value = false;
    result.value = null;
  };

  return {
    loading,
    result,
    executeOneClickEntrust,
    getEntrustList,
    reset
  };
}
